//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import type { AssetInfo, AssetCateInfo } from "@/api/org_asset";
import { ASSET_OWNER_DEPART_MENT, ASSET_OWNER_MEMBER, list_asset_cate, list_depart_ment_asset, list_member_asset, move_asset, remove_asset, update_base_for_asset, update_cate_for_asset } from "@/api/org_asset";
import { useStores } from "@/hooks";
import { request } from "@/utils/request";
import { Button, Input, message, Modal, Space, Table } from "antd";
import type { ColumnsType } from 'antd/lib/table';
import { EditSelect } from "@/components/EditCell/EditSelect";
import { EditOutlined } from "@ant-design/icons";
import { EditText } from "@/components/EditCell/EditText";
import SelectDepartMentModal from "../SelectDepartMentModal";

interface EditAssetDescModalProps {
    assetDesc: string;
    onCancel: () => void;
    onOk: (newDesc: string) => void;
}

const EditAssetDescModal = (props: EditAssetDescModalProps) => {
    const [desc, setDesc] = useState(props.assetDesc);

    return (
        <Modal open title="修改资产备注" mask={false}
            okText="修改" okButtonProps={{ disabled: props.assetDesc == desc }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onOk(desc);
            }}>
            <Input.TextArea autoSize={{ minRows: 3, maxRows: 3 }} value={desc} onChange={e => {
                e.stopPropagation();
                e.preventDefault();
                setDesc(e.target.value);
            }} />
        </Modal>
    );
};

export interface AssetListProps {
    departMentId: string;
    memberUserId?: string;
    dataVersion: number;
}

const AssetList = (props: AssetListProps) => {
    const userStore = useStores("userStore");
    const orgStore = useStores("orgStore");

    const [assetList, setAssetList] = useState<AssetInfo[]>([]);
    const [cateInfoList, setCateInfoList] = useState<AssetCateInfo[]>([]);
    const [editDescAssetInfo, setEditDescAssetInfo] = useState<AssetInfo | null>(null);
    const [moveAssetInfo, setMoveAssetInfo] = useState<AssetInfo | null>(null);
    const [removeAssetInfo, setRemoveAssetInfo] = useState<AssetInfo | null>(null);


    const loadCateInfoList = async () => {
        if (orgStore.curOrgId == "") {
            return;
        }
        const res = await request(list_asset_cate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
        }));

        setCateInfoList(res.cate_list);
    };

    const loadAssetList = async () => {
        if (props.memberUserId !== undefined) {
            const res = await request(list_member_asset({
                session_id: userStore.sessionId,
                org_id: orgStore.curOrgId,
                member_user_id: props.memberUserId,
            }));
            setAssetList(res.asset_list);
        } else {
            const res = await request(list_depart_ment_asset({
                session_id: userStore.sessionId,
                org_id: orgStore.curOrgId,
                depart_ment_id: props.departMentId,
            }));
            setAssetList(res.asset_list);
        }
    };

    const removeAsset = async () => {
        if (removeAssetInfo == null) {
            return;
        }
        await request(remove_asset({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            asset_id: removeAssetInfo.asset_id,
        }));
        const tmpList = assetList.filter(item => item.asset_id != removeAssetInfo.asset_id);
        setAssetList(tmpList);
        message.info("删除成功");
        setRemoveAssetInfo(null);
    };

    const moveAsset = async (newDepartMentId: string) => {
        if (moveAssetInfo == null) {
            return;
        }
        if (newDepartMentId != props.departMentId) {
            await request(move_asset({
                session_id: userStore.sessionId,
                org_id: orgStore.curOrgId,
                asset_id: moveAssetInfo.asset_id,
                owner_type: ASSET_OWNER_DEPART_MENT,
                owner_id: newDepartMentId,
            }));
            await loadAssetList();
        }
        message.info("移动成功");
        setMoveAssetInfo(null);
    };

    const updateAssetDesc = async (newDesc: string) => {
        if (editDescAssetInfo == null) {
            return;
        }
        await request(update_base_for_asset({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            asset_id: editDescAssetInfo.asset_id,
            asset_no: editDescAssetInfo.asset_no,
            asset_desc: newDesc,
        }));
        const tmpList = assetList.slice();
        const index = tmpList.findIndex(item => item.asset_id == editDescAssetInfo.asset_id);
        if (index != -1) {
            tmpList[index].asset_desc = newDesc;
            setAssetList(tmpList);
        }
        message.info("修改成功");
        setEditDescAssetInfo(null);
    };

    const columns: ColumnsType<AssetInfo> = [
        {
            title: "资产编号",
            width: 200,
            render: (_, row: AssetInfo) => (
                <EditText editable={row.user_perm.can_update} content={row.asset_no}
                    onChange={async value => {
                        try {
                            await request(update_base_for_asset({
                                session_id: userStore.sessionId,
                                org_id: orgStore.curOrgId,
                                asset_id: row.asset_id,
                                asset_no: value.trim(),
                                asset_desc: row.asset_desc,
                            }));
                            const tmpList = assetList.slice();
                            const index = tmpList.findIndex(item => item.asset_id == row.asset_id);
                            if (index != -1) {
                                tmpList[index].asset_no = value.trim();
                                setAssetList(tmpList);
                            }
                            return true;
                        } catch (e) {
                            console.log(e);
                            return false;
                        }
                    }} showEditIcon />
            ),
        },
        {
            title: "资产类别",
            width: 120,
            render: (_, row: AssetInfo) => (
                <EditSelect editable={row.user_perm.can_update} curValue={row.asset_cate_id}
                    itemList={cateInfoList.map(item => ({
                        value: item.asset_cate_id,
                        label: item.cate_name,
                        color: "black",
                    }))}
                    onChange={async (value) => {
                        try {
                            await request(update_cate_for_asset({
                                session_id: userStore.sessionId,
                                org_id: orgStore.curOrgId,
                                asset_id: row.asset_id,
                                asset_cate_id: value as string,
                            }));
                            const tmpList = assetList.slice();
                            const index = tmpList.findIndex(item => item.asset_id == row.asset_id);
                            if (index != -1) {
                                tmpList[index].asset_cate_id = value as string;
                                setAssetList(tmpList);
                            }
                            return true;
                        } catch (e) {
                            console.log(e);
                            return false;
                        }
                    }}
                    showEditIcon={true} allowClear={false} />
            ),
        },
        {
            title: "资产归属",
            width: 120,
            render: (_, row: AssetInfo) => (
                <EditSelect editable={row.user_perm.can_move_in_depart_ment || row.user_perm.can_move_global}
                    curValue={row.owner_type == ASSET_OWNER_DEPART_MENT ? "" : row.owner_id}
                    itemList={[
                        {
                            value: "",
                            label: "部门公共资产",
                            color: "black",
                        },
                        ...(orgStore.memberList.filter(item => item.parent_depart_ment_id == props.departMentId).map(item => ({
                            value: item.member_user_id,
                            label: item.display_name,
                            color: "black",
                        })))
                    ]}
                    onChange={async (value) => {
                        const ownerType = value == "" ? ASSET_OWNER_DEPART_MENT : ASSET_OWNER_MEMBER;
                        const ownerId = value == "" ? props.departMentId : value as string;
                        try {
                            await request(move_asset({
                                session_id: userStore.sessionId,
                                org_id: orgStore.curOrgId,
                                asset_id: row.asset_id,
                                owner_type: ownerType,
                                owner_id: ownerId,
                            }));
                            const tmpList = assetList.slice();
                            const index = tmpList.findIndex(item => item.asset_id == row.asset_id);
                            if (index != -1) {
                                tmpList[index].owner_type = ownerType;
                                tmpList[index].owner_id = ownerId;
                                setAssetList(tmpList);
                            }
                            return true;
                        } catch (e) {
                            console.log(e);
                            return false;
                        }
                    }}
                    showEditIcon={true} allowClear={false} />
            ),
        },
        {
            title: "资产备注",
            render: (_, row: AssetInfo) => (
                <Space>
                    <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>{row.asset_desc}</pre>
                    {row.user_perm.can_update && (
                        <Button type="link" icon={<EditOutlined />} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setEditDescAssetInfo(row);
                        }} />
                    )}
                </Space>
            ),
        },
        {
            title: "操作",
            width: 100,
            render: (_, row: AssetInfo) => (
                <Space size="large">
                    {row.user_perm.can_move_global && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setMoveAssetInfo(row);
                        }}>移动</Button>
                    )}
                    {row.user_perm.can_remove && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} danger
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveAssetInfo(row);
                            }}>删除</Button>
                    )}
                </Space>
            ),
        }
    ];

    useEffect(() => {
        loadAssetList();
    }, [props.dataVersion, props.departMentId, props.memberUserId]);

    useEffect(() => {
        loadCateInfoList();
    }, []);

    return (
        <>
            <Table rowKey="asset_id" dataSource={assetList} columns={columns} pagination={false} />
            {editDescAssetInfo != null && (
                <EditAssetDescModal assetDesc={editDescAssetInfo.asset_desc} onCancel={() => setEditDescAssetInfo(null)}
                    onOk={newDesc => updateAssetDesc(newDesc)} />
            )}
            {moveAssetInfo != null && (
                <SelectDepartMentModal skipDepartMentIdList={[props.departMentId]} onCancel={() => setMoveAssetInfo(null)}
                    onOk={newDepartMentId => moveAsset(newDepartMentId)} />
            )}
            {removeAssetInfo != null && (
                <Modal open title="删除资产" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveAssetInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeAsset()
                    }}>
                    是否删除资产&nbsp;{removeAssetInfo.asset_no}({removeAssetInfo.cate_name})&nbsp;?
                </Modal>
            )}
        </>
    );
};

export default observer(AssetList);